package com.znsd.exam.controllor;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.znsd.entitys.ExamPaperInfo;
import com.znsd.entitys.ExamPlan;
import com.znsd.entitys.ExamSubjectMiddleInfo;
import com.znsd.entitys.QuestionInfo;
import com.znsd.entitys.SearchInfo;
import com.znsd.entitys.SpecialtyInfo;
import com.znsd.entitys.Subjectinfo;
import com.znsd.entitys.Users;
import com.znsd.exam.service.ExamPaperService;
import com.znsd.exam.service.ExamPlanService;
import com.znsd.exam.service.ExamSubjectMiddleService;
import com.znsd.exam.service.QuestionService;
import com.znsd.exam.service.SpecialtyService;
import com.znsd.exam.service.SubjectServicePan;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class ExamPaperControllorPan {
	@Autowired
	private ExamPaperService examPaperService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private SpecialtyService specialtyService;
	@Autowired
	private SubjectServicePan subjectServicePan;
	@Autowired
	private ExamSubjectMiddleService examSubjectMiddleService;
	@Autowired
	private ExamPlanService examPlanService;
	
	private static List<Integer> str=new ArrayList<Integer>();
	
	private static String paperName;
	private static String addTimeStart;
	private static String addTimeEnd;
	
	@RequestMapping(value = "/examPapers",method = RequestMethod.GET)
	public ModelAndView examPapers(
			@RequestParam(value="startPage", required=false, defaultValue="1") Integer startPage,
			@RequestParam(value="pageShow", required=false, defaultValue="10") Integer pageShow,SearchInfo search){
		ModelAndView model=new ModelAndView();
		Map<String, Object> map=new HashMap<String, Object>();
		Map<String, Object> map1=new HashMap<String, Object>();
		Integer examPaperTotal = 0;
		if(startPage==1&&(search.getPaperName()!=null||search.getAddTimeEnd()!=null||search.getAddTimeStart()!=null)) {
			paperName=null;
			addTimeStart=null;
			addTimeEnd=null;
		}
		if(search.getPaperName()!=null&&search.getPaperName()!="") {
			paperName=search.getPaperName();
		}if(search.getAddTimeStart()!=null&&search.getAddTimeStart()!="") {
			addTimeStart=search.getAddTimeStart();
		}if(search.getAddTimeEnd()!=null&&search.getAddTimeEnd()!="") {
			addTimeEnd=search.getAddTimeEnd();
		}
		System.out.println("========="+paperName+"========="+addTimeStart+"========="+addTimeEnd);
		map1.put("paperName", paperName);
		map1.put("addTimeStart",addTimeStart);
		map1.put("addTimeEnd", addTimeEnd);
		map1.put("pageIndex", (startPage-1) * pageShow);
		map1.put("pageStart", pageShow);
		//计算试卷总数
		examPaperTotal = examPaperService.getCount(map1);
		List<ExamPaperInfo> list = examPaperService.getList(map1);
		map.put("list", list);
		model.addObject("map", list);
		//计算总页数
		int pageTotal = 1;
		if (examPaperTotal % pageShow == 0) {
			pageTotal = examPaperTotal / pageShow;
		}else {
			pageTotal = examPaperTotal / pageShow + 1;	
		}
		model.addObject("pageTotal", pageTotal);
		model.addObject("pageNow", startPage);
		model.setViewName("admin/examPapers");
		return model;
	}
	@RequestMapping("/examPaperedit")
	public ModelAndView examPaperedit(Integer examPaperId,HttpServletRequest request) {
		ModelAndView model=new ModelAndView();
		List<QuestionInfo> list = questionService.getList();
		if(examPaperId != null) {
			ExamPaperInfo examPaper = examPaperService.getOne(examPaperId);
			model.addObject("examPaper", examPaper);
		}
		model.addObject("list", list);
		model.setViewName("admin/examPaperedit");
		return model;
	}
	@ResponseBody
	@RequestMapping("/examPapereditAdd")
	public boolean examPapereditAdd(Integer examPaperId) {
		return true;
	}
	//判断修改email
	@ResponseBody
	@RequestMapping("/getexamPaperedit")
	public boolean getexamPaperedit(Integer examPaperId,HttpServletRequest request) {
		if(examPaperId != null) {
			HttpSession session = request.getSession();
			Users user = (Users) session.getAttribute("user");
			ExamPaperInfo examPaper = examPaperService.getOne(examPaperId);
			if(examPaper.getCreator().equals(user.getUser_mail())) {
				return true;
			}
		}
		return false;
	}
	@RequestMapping(value = "/examPaperAdd",method = RequestMethod.POST)
	public String examPaperAdd(ExamPaperInfo examPaper,HttpServletRequest request) {
		HttpSession session = request.getSession();
		Users user = (Users) session.getAttribute("user");
		examPaper.setCreator(user.getUser_mail());
		examPaper.setEstablishTime(new Date());
		Integer index = examPaperService.save(examPaper);
		//System.out.println(index+"===========增加===="+examPaper.getExamPaperId()+user);
		for (int i = 0; i < str.size(); i++) {
			ExamSubjectMiddleInfo esm=new ExamSubjectMiddleInfo();
		    esm.setSubjectId(str.get(i));
		    esm.setExamPaperId(examPaper.getExamPaperId());
		    examSubjectMiddleService.save(esm);
		}
		str.clear();
		System.out.println("str:    "+str);
		return "admin/examPapers";
	}
	@RequestMapping(value = "/examPaperUpdate",method = RequestMethod.POST)
	public String examPaperUpdate(ExamPaperInfo examPaper) {
		Integer index = examPaperService.update(examPaper);
		//System.out.println(index+"==========修改====="+examPaper);
		return "admin/examPapers";
	}
	@RequestMapping(value = "/examPaperDelete/{examPaperId}",method = RequestMethod.DELETE)
	public String examPaperDelete(@PathVariable("examPaperId")Integer examPaperId) {
		Integer index = examPaperService.delete(examPaperId);
		//System.out.println(index+"==========删除====="+examPaperId);
		return "redirect:/examPapers";
	}
	@ResponseBody
	@RequestMapping(value = "/getexamPaperDelete/{examPaperId}", method = RequestMethod.GET)
	public boolean getExamPaperDelete(@PathVariable("examPaperId")Integer examPaperId) {
		List<ExamPlan> list = examPlanService.getOne(examPaperId);
		if(list.size() != 0) {
			return false;
		}else {
			return true;
		}
	}
	@ResponseBody
	@RequestMapping(value = "/getESM", method = RequestMethod.GET)
	public Map<String,Object> getESM(Integer examPaperId) {
		List<ExamSubjectMiddleInfo> list = examSubjectMiddleService.getOne(examPaperId);
		System.out.println("----");
		List<Integer> li=new ArrayList<Integer>();
		for (ExamSubjectMiddleInfo esm : list) {
			if(esm.getSubjectId() != null && !"".equals(esm.getSubjectId())) {
				li.add(esm.getSubjectId());
			}
		}
		List<Subjectinfo> list1 = subjectServicePan.getin(li);
		Map<String, Object> map=new HashMap<String, Object>();
		if(list1 == null) {
			return null;
		}
		map.put("list", list1);
		return map;
	}
	@ResponseBody
	@RequestMapping(value = "/getSpecialty", method = RequestMethod.GET)
	public Integer getSpecialty(Integer specialty_id,Integer number) {
		Integer count = subjectServicePan.getAll(specialty_id);
		if(number != null && number > count) {
		    return -1;
		}else if(number != null && number < 0) {
			return -2;
		}
		return count;
	}
	@ResponseBody
	@RequestMapping(value = "/getSpecialtySubmit", method = RequestMethod.GET)
	public Map<String, Object> getSpecialtySubmit(String idata) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> m=new HashMap<String, Object>();
		if(idata != null){
			 JSONArray jsonArray=JSONArray.fromObject("["+idata+"]");
			 for(Object o : jsonArray){
				 map=JSONObject.fromObject(o);
			 }
			 Integer countSubject = 0; //总题数
			 Integer countFraction = 0;//总分数
			 for(String key : map.keySet()) {
				 if(!"".equals(map.get(key)) && map.get(key) != null && Integer.parseInt(map.get(key).toString()) > 0) {
						Integer parseInt = Integer.parseInt(map.get(key).toString());
						countSubject+=parseInt;
						Integer sub = Integer.parseInt(key.substring(3).toString());
						Map<String, Object> map1 = new HashMap<String, Object>();
						map1.put("specialtyId", sub);
						map1.put("pageStart", Integer.parseInt(map.get(key).toString()));
						List<Subjectinfo> list = subjectServicePan.getStatisticalScore(map1);
						Integer score = 0;
						for (Subjectinfo s : list) {
							Integer sCount = Integer.valueOf(s.getSubjectScore());
							score+=sCount;
							str.add(Integer.parseInt(s.getSubjectId().toString()));
							System.out.println("题目id:    "+s.getSubjectId());
						}
						countFraction+=score;
						System.out.println("key:"+key+ "  value:"+map.get(key)+"    sub:  "+sub);
					}
			 }
			 m.put("countSubject", countSubject);
			 m.put("countFraction", countFraction);
			 if(countSubject <= 50) {
				 m.put("falg", true);
			 }else {
				 m.put("falg", false);
			 }
		}
		return m;
	}
	@ResponseBody
	@RequestMapping(value = "/getExampPaperCourse", method = RequestMethod.GET)
	public List<SpecialtyInfo> courseList() {
		List<SpecialtyInfo> courseList = specialtyService.getCourseList();
		return courseList;
	}

	@ResponseBody
	@RequestMapping(value = "/getExampPaperChapter/{cid}", method = RequestMethod.GET)
	public List<SpecialtyInfo> chapterList(@PathVariable("cid") Integer cid) {
		return specialtyService.getChapterList(cid);
	}
	@ResponseBody
	@RequestMapping(value = "/getExampPaperPoints/{cid}", method = RequestMethod.GET)
	public List<SpecialtyInfo> pointsList(@PathVariable("cid") Integer cid) {
		return specialtyService.getPointsList(cid);
	}
}
